using System;
using System.Configuration;
using System.Reflection;
using Microsoft.Rtc.Collaboration;
using Microsoft.Rtc.Signaling;
using log4net;

namespace Lync.Widget.Library.InstantMessaging
{
    public abstract class UCInstantMessageRouterBase
    {
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        protected static CollaborationPlatform CollabPlatform;

        protected UCInstantMessageRouterBase()
        {
            const SipTransportType transportType = SipTransportType.Tls;
            var clientPlatformSettings = new ClientPlatformSettings(ConfigurationManager.AppSettings["ApplicationName"], transportType);
            CollabPlatform = new CollaborationPlatform(clientPlatformSettings);
            CollabPlatform.BeginStartup(EndPlatformStartup, CollabPlatform);
        }

        private void EndPlatformStartup(IAsyncResult ar)
        {
            var collabPlatform = ar.AsyncState as CollaborationPlatform;
            try
            {
                // The platform should now be started.
                collabPlatform.EndStartup(ar);
                // It should be noted that all the re-thrown exceptions will crash the application. This is intentional.
                // Ideal exception handling would report the error and shut down nicely. In production code, consider using 
                // an IAsyncResult implementation to report the error instead of throwing or put the implementation
                // in this try block.
            }
            catch (OperationFailureException opFailEx)
            {
                // OperationFailureException will be thrown when the platform cannot establish, here, usually due to invalid data.
                Log.Error("OperationFailureException", opFailEx);
                throw;
            }
            catch (ConnectionFailureException connFailEx)
            {
                // ConnectionFailureException will be thrown when the platform cannot connect.
                // ClientPlatforms will not throw this exception on startup.
                Log.Error("ConnectionFailureException", connFailEx);
                throw;
            }
            catch (RealTimeException realTimeEx)
            {
                // RealTimeException may be thrown as a result of any UCMA operation.
                Log.Error("RealTimeException", realTimeEx);
                throw;
            }
        }
    }
}